package com.gree.portal.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.gree.commom.result.BaseResult;
import com.gree.rpc.entity.Admin;
import com.gree.rpc.service.CartService;
import com.gree.rpc.vo.CartResult;
import com.gree.rpc.vo.CartVo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
 * 购物车控制器
 */
@Controller
@RequestMapping("/cart")
public class CartController {

    @Reference(interfaceClass = CartService.class)
    private CartService cartService;

    /**
     * 添加购物车
     * @param cartVo
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     * @throws JsonProcessingException
     */
    @RequestMapping("/addCart")
    @ResponseBody
    public BaseResult addCart(CartVo cartVo, HttpServletRequest request) throws Exception {
        cartVo.setAddTime(new Date());
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        BaseResult baseResult = cartService.addCart(cartVo, admin);
        return baseResult;
    }

    /**
     * 获取购物车数量
     */
    @RequestMapping("/getCartNum")
    @ResponseBody
    public Integer getCartNum(HttpServletRequest request) throws Exception {
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        return cartService.getCartNum(admin);
    }

    /**
     * 获取购物车列表信息
     * 跳转至购物车
     */
    @RequestMapping("/getCartList")
    public String getCartList(HttpServletRequest request, Model model){
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        CartResult cartResult = cartService.getCartList(admin);
        model.addAttribute("cartResult",cartResult==null?new CartResult():cartResult);
        return "cart/list";
    }
}
